﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CQ.Framework.APIService;
using MvcBJDCWebApp.DAL;
using MvcBJDCWebApp.Models.API;
using MvcBJDCWebApp.Models.League;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MvcBJDCWebApp.Controllers
{
    public class LeaguesController : Controller
    {
        private LeagueContext db = new LeagueContext();
        private IAPIHelper ApiHelper;

        public LeaguesController(IAPIHelper helper)
        {


            ApiHelper = helper;
        }

        public ActionResult Indexddd(string league)
        {
            if (string.IsNullOrEmpty(league))
            {
                league = "中超";
            }

            GetAPIData(ApiHelper, league);

            return View(db.Leagues.ToList());
        }

        // GET: Leagues
        public ActionResult Index(string league)
        {       
            return View(db.Leagues.ToList());
        }

        // GET: Leagues/Details/5
        public ActionResult Details(int? id,int? leagueTypeID)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }


            if (leagueTypeID != null && leagueTypeID > 0)
            {
                //get the detail 

                return View(db.LeagueDetails.Where(c => c.LeagueTypeID == leagueTypeID).ToList());
            }

            League league = db.Leagues.Find(id);
            if (league == null)
            {
                return HttpNotFound();
            }
            return View(league);
        }

        // GET: Leagues/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Leagues/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "LeagueID,LeagueKey")] League league)
        {
            if (ModelState.IsValid)
            {
                db.Leagues.Add(league);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(league);
        }

        // GET: Leagues/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            League league = db.Leagues.Find(id);
            if (league == null)
            {
                return HttpNotFound();
            }
            return View(league);
        }

        // POST: Leagues/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "LeagueID,LeagueKey")] League league)
        {
            if (ModelState.IsValid)
            {
                db.Entry(league).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(league);
        }

        // GET: Leagues/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            League league = db.Leagues.Find(id);
            if (league == null)
            {
                return HttpNotFound();
            }
            return View(league);
        }

        // POST: Leagues/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            League league = db.Leagues.Find(id);
            db.Leagues.Remove(league);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private void GetAPIData(IAPIHelper aPIHelper,string league)
        {
            string appkey = System.Configuration.ConfigurationManager.AppSettings["apiKey"].ToString();

            string url = "http://op.juhe.cn/onebox/football/league";

            var para = new Dictionary<string, string>();

            para.Add("key", appkey);//你申请的key
            para.Add("dtype", ""); //返回数据的格式,xml或json，默认json
            para.Add("league", league); //联赛名称

            JObject json = aPIHelper.GetAPIData(appkey, url, para);

            SerJson(json);

            //db.APIRaces.Add(aPIRace);
            //db.SaveChanges();
            //return RedirectToAction("Index");
        }

        private void SerJson(JObject jsonApi)
        {
            //APIQuery Deserialize JSON Object

            //Student stu2 = JsonConvert.DeserializeObject<Student>(json1);

            // initial view object
            //var views = jsonApi["result"]["views"].ToString();

            //APIView apiView = JsonConvert.DeserializeObject<APIView>(views);

            //var time = jsonApi["reason"].ToString();

            //get tabs
            //var tabs = jsonApi["result"]["tabs"];
            ////tabs["saicheng1"]


            //// initial data
            League league = new League();            

            // set key
            league.LeagueKey = jsonApi["result"]["key"].ToString();

            //release data
            DeleteData(league.LeagueKey);

            //set type
            ICollection<LeagueType> leagueTypes = new List<LeagueType>();

            foreach(var key in APITabKey.TabKeys)
            {
                var leagueType = BuildLeagueType(jsonApi, key);

                leagueTypes.Add(leagueType);
            }

           
           

            league.LeagueType = leagueTypes;          

            //save 
            db.Leagues.Add(league);
            db.SaveChanges();
             //RedirectToAction("Index");

        }

        private LeagueType BuildLeagueType(JObject jsonApiData,string tabKey)
        {
            LeagueType leagueType = new LeagueType();
            //JsonConvert.DeserializeObject<APIView>(views);
            //get tabs
            var tabs = jsonApiData["result"]["tabs"];
            var views = jsonApiData["result"]["views"];


            // build type
            leagueType.Type = tabs[tabKey].ToString();

            // build detail
            var leagueDetails = JsonConvert.DeserializeObject<ICollection<LeagueDetail>>(views[tabKey].ToString());
            leagueType.LeagueDetails = leagueDetails;


            return leagueType;
        }

        private void DeleteData(string leagueKey)
        {
            //Course course = db.Courses.Find(id);
            //League league=db.Leagues.Find()
            IQueryable<League> league = db.Leagues
                                .Where(c => c.LeagueKey == leagueKey);


            foreach (var leg in league.ToList())
            {
                db.Leagues.Remove(leg);
            }

            

        }

        
    }
}
